package com.cskaoyan.service;

import com.cskaoyan.bean.MarketSystem;
import com.cskaoyan.bean.MarketSystemExample;
import com.cskaoyan.mapper.MarketSystemMapper;
import com.cskaoyan.util.MyBatisUtil;
import com.cskaoyan.util.TransactionUtil;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author stone
 * @date 2023/03/20 15:26
 */
public class SystemConfigServiceImpl implements SystemConfigService {

    @Override
    public Map<String, String> listMall() {
        MarketSystemMapper systemMapper = MyBatisUtil.getMapper(MarketSystemMapper.class);
        MarketSystemExample example = new MarketSystemExample();
        example.or().andKeyNameLike("market_mall_%").andDeletedEqualTo(false);
        List<MarketSystem> systemList = systemMapper.selectByExample(example);
        Map<String, String> map = systemList.stream().collect(Collectors.toMap(MarketSystem::getKeyName, MarketSystem::getKeyValue));

        return map;
    }

    @Override
    public int updateConfig(Map<String, String> data) {
        TransactionUtil.startTransaction();
        MarketSystemMapper systemMapper = TransactionUtil.getMapper(MarketSystemMapper.class);
        int i = 0;
        try {
            i = 0;
            for (Map.Entry<String, String> entry : data.entrySet()) {
                MarketSystemExample example = new MarketSystemExample();
                example.createCriteria().andKeyNameEqualTo(entry.getKey()).andDeletedEqualTo(false);

                MarketSystem system = new MarketSystem();
                //system.setKeyName(entry.getKey());
                system.setKeyValue(entry.getValue());
                system.setUpdateTime(new Date());
                i += systemMapper.updateByExampleSelective(system, example);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            TransactionUtil.rollback();
        }
        TransactionUtil.commit();
        return i;
    }
}
